from marshmallow import fields, post_load
from gis.common.django_ext.forms import BaseSchema, PaginationSchema, OptionField


class RegisterSchema(BaseSchema):
    name = fields.String(required=True)
    password = fields.String(required=True)

    @post_load
    def post_load_func(self, data):
        data["name"] = data["name"].strip()
        return data


class LoginSchema(BaseSchema):
    name = fields.String(required=True)
    password = fields.String(required=True)


class AddUserSchema(BaseSchema):
    name = fields.String(required=True)
    password = fields.String(required=True)
    enable = fields.Boolean(missing=False)
    role_ids = fields.List(fields.Integer())
    parent_id = fields.Integer()


class GetUserSchema(PaginationSchema):
    order_by = OptionField(["last_login_at", "-last_login_at"], required=False)
    name = fields.String()
    enable = fields.Boolean()
    role_id = fields.Integer()


class UpdateUserSchema(BaseSchema):
    role_ids = fields.List(fields.Integer())
    enable = fields.Boolean(allow_none=True)


class UpdateUserPasswordSchema(BaseSchema):
    old_password = fields.String(required=True)
    new_password = fields.String(required=True)


class RolePermissionRelSchema(BaseSchema):
    permission_id = fields.Integer(required=True)
    include_fields = fields.List(fields.String(required=True))


class AddRoleSchema(BaseSchema):
    name = fields.String(required=True)
    desc = fields.String()
    permissions = fields.List(fields.Nested(RolePermissionRelSchema))


class UpdateRoleSchema(BaseSchema):
    name = fields.String(required=True)
    desc = fields.String()
    permissions = fields.List(fields.Nested(RolePermissionRelSchema))


class RecordListSchema(PaginationSchema):
    resource = fields.String(allow_none=True)
    operator = fields.Integer()
    action = fields.Integer()
    ip = fields.String()
    created_at_begin = fields.DateTime()
    created_at_end = fields.DateTime()
